package top.kaoshanji.p1ch03a;

import org.apache.hc.client5.http.fluent.Content;
import org.apache.hc.client5.http.fluent.Form;
import org.apache.hc.client5.http.fluent.Request;
import org.apache.hc.core5.http.ContentType;
import top.kaoshanji.p1util.ClientAppConfig;
import top.kaoshanji.p1util.ConfigUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;

/**
 * 代码清单-p1ch03a-02：授权服务器携带授权码重定向-->获取token-->资源API
 * @author kaoshanji
 * ^_^
 * create time 2025/5/25 14:04
 */
@WebServlet(urlPatterns = {"/callback"})
public class CallbackServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置请求对象的编码
        req.setCharacterEncoding(StandardCharsets.UTF_8.name());

        // 1、获取授权码
        String code = req.getParameter("code");
        System.out.println("...授权服务器返回的授权码..." + code);

        ClientAppConfig clientAppConfig = ConfigUtil.getClientAppConfig();

        // 2、客户端向授权服务器POST表单提交
        Request requestCode = Request.post(clientAppConfig.getTokenUri());
        requestCode.bodyForm(Form.form()
                .add("client_id", clientAppConfig.getClientId())
                .add("client_secret", clientAppConfig.getClientSecret())
                .add("code", code)
                .build());

        Content contentCode = requestCode.execute().returnContent();
        String token = contentCode.asString();

        System.out.println("...向授权服务器请求访问令牌的响应..."+token);

        // 3、向受保护资源请求API
        Request requestResource = Request.post(clientAppConfig.getResourceUri()+"hi");
        requestResource.bodyForm(Form.form()
                .add("token", token)
                .build());

        Content contentResource = requestResource.execute().returnContent();
        String resource = contentResource.asString(StandardCharsets.UTF_8);

        System.out.println("...向受保护资源请求API的响应..."+resource);

        // 设置响应对象的编码和内容格式
        resp.setContentType(ContentType.TEXT_HTML.toString());
        PrintWriter out = resp.getWriter();

        out.println("<HTML>");
        out.println("<HEAD><TITLE>OAuth2.0简单版本</TITLE></HEAD>");
        out.println("<BODY>");
        out.println("<BIG>授权码："+code+"</BIG><br/>");
        out.println("<BIG>token："+token+"</BIG><br/>");
        out.println("<BIG>资源API响应："+resource+"</BIG><br/>");
        out.println("</BODY></HTML>");

    }

}
